package tom.adminlte.config;

import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

/**
 * 存在redis存储序列化问题，方法二,
 * 自定义RedisTemplate并设置序列化组件，根据redisTemplate创建RedisOperationsSessionRepository
 * @author ZHUFEIFEI
 */
//@Configuration
//@EnableRedisHttpSession
public class RedisSessionConfig2 {

    @Bean
    public SpringSessionBackedSessionRegistry sessionRegistry(RedisTemplate<Object, Object> redisTemplate) {
        return new SpringSessionBackedSessionRegistry(new RedisOperationsSessionRepository(redisTemplate));
    }
    /**
     * 自定义 redisTemplate替换默认的redisTemplate， 解决序列化问题
     * 默认的key和hash key序列化采用的的JdkSerializationRedisSerializer，
     * 对key序列化后值前面多\xac\xed\x00\x05sr\x00\x0..., 导致无法正常清理session，因为key值不对
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    @Primary
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        //key和hash key的序列化采用String序列化类
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setBeanClassLoader(this.getClass().getClassLoader());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


}
